package com.itcast.rpc.client.runner;

import com.itcast.common.data.RpcRequest;
import com.itcast.common.data.RpcResponse;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 消息处理
 */
@Component
public class RequestPool {

    private final ConcurrentHashMap<String, Promise<RpcResponse>> requestPool = new ConcurrentHashMap<>();

    public void submitRequest(String requestId, EventExecutor executor){
        requestPool.put(requestId,new DefaultPromise<>(executor));
    }

    public RpcResponse fetchResponse(String requestId){
        Promise<RpcResponse> rpcResponsePromise = requestPool.get(requestId);
        if (rpcResponsePromise!=null){
            try {
                RpcResponse rpcResponse = rpcResponsePromise.get(10, TimeUnit.SECONDS);
                RpcRequestManager.destoryChannelHolder(requestId);
                requestPool.remove(requestId);
                return rpcResponse;
            }  catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public void notifyRequest(String requestId, RpcResponse response){
        Promise<RpcResponse> rpcRequestPromise = requestPool.get(requestId);
        if (rpcRequestPromise != null){
            rpcRequestPromise.setSuccess(response);
        }
    }

}
